<template>
  <div class="article-detail">
    <el-card shadow="never" class="margin-30">
      <div slot="header">
        <span> {{ articleId?'修改文章':'立即新增' }}</span>
      </div>
      <el-form ref="form" :model="article" :rules="rules" label-width="120px" size="small">
        <el-row :gutter="20">
          <el-col :span="6" :offset="0">
            <el-form-item label="作者" prop="author">
              <el-input v-model="article.author" placeholder="作者" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="标题" prop="title">
              <el-input v-model="article.title " placeholder="标题" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="是否显示">
              <!-- isShow (integer, optional): 是否显示: 0 否; 1 是 , -->
              <el-switch v-model="article.isShow" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="13" :offset="0">
            <el-form-item label="摘要">
              <el-input v-model="article.summary" :rows="3" type="textarea" placeholder="摘要" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="13" :offset="0">
            <el-form-item label="封面图片">
              <el-upload
                ref="coverImgUpload"
                :action="uploadFileOss"
                :headers="token"
                :on-success="coverImgUploadSucc"
                :before-upload="beforeCoverImgUpload"
              >
                <img v-if="article.coverImg" :src="article.coverImg" width="100" alt="">
                <el-button v-else size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif/webp/jpeg文件，且不超过1.5M</div>
              </el-upload>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="13" :offset="0">
            <el-form-item label="切换富文本类型">
              <!-- editorType (integer, optional): 编辑器类型: 0 富文本; 1 markdown , -->
              <el-radio v-model="article.editorType" :label="0" @input="changEditorType">富文本</el-radio>
              <el-radio v-model="article.editorType" :label="1" @input="changEditorType">markdown</el-radio>
              <span style="color:#e6a23c;"> <i class="el-icon-warning" /> 注意!切换编辑器会清空编辑内容</span>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <div v-if="article.editorType===0">
              <Tinymce v-model="article.content1" />
            </div>
            <div v-if="article.editorType===1">
              <mavon-editor ref="mavonEditor" v-model="article.content1" @imgAdd="$imgAdd" />
            </div>

          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="doAddOrUpdateArticle">
            {{ articleId?'修改文章':'立即新增' }}
          </el-button>

        </el-form-item>
      </el-form>

    </el-card>

  </div>
</template>
<script>
import axios from 'axios'
import Tinymce from '@/components/Tinymce'

import { addArticle as addArticleApi,
  productArticle as productArticleApi,
  updateArticle as updateArticleApi } from '@/api/article'
import mix from '@/mixins'
export default {
  name: 'AddOrEditArticle',
  components: {
    Tinymce

  },
  mixins: [mix],
  data() {
    return {
      articleId: '',
      article: {
        isShow: 1,
        editorType: 0,
        coverImg: ''
      },
      rules: {
        author: [{ required: true, message: '作者必填', trigger: 'blur' }],
        title: [{ required: true, message: '标题必填', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.articleId = this.$route.query.id
    if (this.articleId) { // 从编辑文章 进来
      this.getArticleDetail()
    }
  },

  methods: {
    // 获取文章详情
    async getArticleDetail() {
      const res = await productArticleApi(this.articleId)
      const { success, data, message } = res
      if (success) {
        // 回显数据
        this.article = data.productArticle
      } else {
        this.$message.error(message)
      }
    },
    // 封面图上传成功
    coverImgUploadSucc(response) {
      this.article.coverImg = response.data.fileUrl
      // 清空列表
      this.$refs.coverImgUpload.clearFiles()
    },
    // 封面图上传前校验
    beforeCoverImgUpload(file) {
      // jpg/png/gif/webp/jpeg
      const reg = /^image\/(jpe?g|png|gif|webp)$/
      // const isJPG = file.type === 'image/jpeg'
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5
      const isImg = reg.test(file.type)
      if (!isImg) {
        this.$message.error('上传头像图片只能是 jpg/png/gif/webp/jpeg 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      return isImg && isLt1dot5M
    },
    // 编辑器类型改变
    changEditorType() {
      this.article.content1 = ''
    },
    // 新增 / 修改 文章
    async doAddOrUpdateArticle() {
      if (this.article.editorType === 0) {
        // 富文本的 conttent1 和 content2 一样
        this.article.content2 = this.article.content1
      }
      if (this.article.editorType === 1) { // markdown
        console.log('this.$refs.mavonEditor==>', this.$refs.mavonEditor)
        this.article.content2 = this.$refs.mavonEditor.d_render
      }
      let api = null
      if (this.articleId) { // 修改
        api = updateArticleApi
      } else { // 新增
        api = addArticleApi
      }
      // 表单校验
      this.$refs['form'].validate(async(valid) => {
        if (valid) { // 校验通过
          const res = await api(this.article)
          const { success, message } = res
          if (success) {
            // 返回文章列表
            this.$router.push({ name: 'Article' })
          } else {
            this.$message.error(message)
          }
        } else {
          this.$message.error('请注意表单校验！')
          return false
        }
      })
    },
    // markdown上传图片 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      // formdata.append('image', $file)
      formdata.append('file', $file)
      axios({
        url: this.uploadFileOss,
        method: 'post',
        data: formdata,
        headers: this.token
      }).then((res) => {
        console.log('res=>', res)
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        /**
               * $vm 指为mavonEditor实例，可以通过如下两种方式获取
               * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
               * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
               */
        this.$refs.mavonEditor.$img2Url(pos, res.data.data.fileUrl)
      })
    }
  }

}
</script>
<style lang="scss" scoped>
</style>
